package com.blog.blog.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import com.blog.blog.dao.pojo.SysUser;
import com.blog.blog.service.SysUserService;
import com.blog.blog.utils.JWTUtil;
import com.blog.blog.utils.UserThreadLocal;
import com.blog.blog.vo.ErrorCode;
import com.blog.blog.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 1.需要判断 请求的接口路径是否为HanderMethod(Controller方法)
     * 2.判断token是否为空，如果为空 未登录
     * 3.如果token不为空，验证token
     * 4.如果认证成功 放行即可
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是Controller方法就放行
        if (!(handler instanceof HandlerMethod)) {
            //handler 可能是访问静态资源的handler
            return true;
        }
        String token= request.getHeader("token");
        //判断token是否为空，如果为空 未登录
        if (StringUtils.isBlank(token)) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (StringUtils.isBlank(userJson)){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(),ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        Map<String, Claim> checkToken = JWTUtil.checkToken(token);
        if (checkToken == null) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(),ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        UserThreadLocal.put(sysUser);
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                sysUser, sysUser.getPassword(), sysUserService.getAuthorities(sysUser.getId()));
        SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
        return true;
    }

    /**
     * 调用前提：preHandle返回true
     * 调用时间：DispatcherServlet进行视图的渲染之后
     * 多用于清理资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //如果不删除 ThreadLocal中用完的信息 会有内存泄露的风险
        UserThreadLocal.remove();
    }
}
